﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using UnityEngine;

public class GameInit : MonoBehaviour
{
    public static GameInit instance;

    private Slot slotPrefab;

    /// <summary>
    /// 地图具体内容
    /// </summary>
    private string[,] map;

    public float amount;//分数

    /// <summary>
    /// 存放地图数据的字典
    /// </summary>
    public Dictionary<string, List<Slot>> numberSlotsDict = new Dictionary<string, List<Slot>>();
    /// <summary>
    /// 记录被涂鸦的数量
    /// </summary>
    public Dictionary<string, int> paintedCountDict = new Dictionary<string, int>();

    ///完成一个数字的涂鸦后就生成特效
    //public GameObject numberCompleteEffect;

    /// <summary>
    /// 需要完成的数量，当前完成的数量
    /// </summary>
    private int need_num, current_num;
    /// <summary>
    /// 当前关卡
    /// </summary>
    public MapData MapData = new MapData();
    /// <summary>
    /// 当前所有slot
    /// </summary>
    public List<Slot> Slot_list;


    /// <summary>
    /// slot对象池
    /// </summary>
    private Queue<Slot> objectPool = new Queue<Slot>();
    private List<Slot> activeSlots = new List<Slot>();
    /// <summary>
    /// 结算效果
    /// </summary>
    public ParticleSystem SettlementEffect;
    /// <summary>
    /// 分块相机起始位置
    /// </summary>
    public Dictionary<int, Vector3> StartPosition { get; private set; }

    /// <summary>
    /// 分块
    /// </summary>
    private Dictionary<int, List<Slot>> Slot_lists = new Dictionary<int, List<Slot>>();
    /// <summary>
    /// 当前区块编号
    /// </summary>
    private int currentPiece = 1, upcurrentPiece=1;
    /// <summary>
    /// 区块大小
    /// </summary>
    private int col = 0;
    private int row = 0;

    void Awake()
    {
        instance = this;
        slotPrefab = Resources.Load<Slot>("Prefab/Slot");
    }

    private void Start()
    {
        for (int i = 0; i < 1500; i++)
        {
            CreateNewObject();
        }
        StartCoroutine(NewObject());
    }


    public int CurrentPiece()
    {
        return currentPiece;
    }

    public int Col()
    {
        return col;
    }
    public int Row()
    {
        return row;
    }

    private IEnumerator NewObject()
    {
        for (int i = 0; i <1000; i++)
        {
            CreateNewObject();

            // 每创建10个对象等待一帧
            if (i % 100 == 0)
            {
                yield return null; // 等待一帧
            }
        }
        // 协程结束
        yield break;
    }

    /// <summary>
    /// 进入地图
    /// </summary>
    /// <param name="column"></param>
    /// <param name="row"></param>
    /// <param name="m"></param>
    public void SetMap(MapData mapData)
    {
        StopAllCoroutines();
        ReturnAllSlots();
        StartCoroutine(RestoreUICoroutine());
        ChangePanel.changePanel.Open_The_next_level_Button(false);

        numberSlotsDict = new Dictionary<string, List<Slot>>();
        paintedCountDict = new Dictionary<string, int>();


        MapData = mapData;
        map = MapData.mapArray;
        need_num = MapData.mapArray.Length;
        current_num = 0;
        currentPiece = 1;
        upcurrentPiece = 1;
        Vector3 startPos = new Vector3(0, 0, 0);
        int num = 0;
        Slot_list = new List<Slot>();
        for (int z = 0; z < MapData.rows; z++)
        {
            for (int x = 0; x < MapData.columns; x++)  // 从左到右（x对应列）
            {
                Vector3 position = new Vector3(
                    startPos.x + x * 1f,
                    startPos.y+0.5f,
                    startPos.z - z * 1f
                );
                num++;
                Slot slot = GetObject();
                slot.transform.position = position;
                slot.SetNumber(map[z, x].ToString(), num);
                string number = slot.id;
                if (int.TryParse(number, out int value))
                {
                    slot.Change_color(value * 0.08f);
                }
                else if (char.IsLetter(number[0]))
                {
                    char letter = char.ToUpper(number[0]);
                    value = letter - 'A' + 1;
                    slot.Change_color(value * 0.08f);
                }
                else
                {
                    // 既不是数字也不是单个字母，可以给默认值或忽略
                    slot.Change_color(0f); // 例如黑色或默认颜色
                }

                // 统计数字分布
                if (!numberSlotsDict.ContainsKey(number))
                {
                    numberSlotsDict.Add(number, new List<Slot>());
                    numberSlotsDict[number].Add(slot);
                    paintedCountDict.Add(number, 0);
                } else
                {
                    numberSlotsDict[number].Add(slot);
                }
                Slot_list.Add(slot);

                //slot.gameObject.SetActive(false);
            }
        }

        for (int j = 0; j < Slot_list.Count; j++)
        {
            if (ReadData.instance.loadedData.ContainsKey(MapData.id))
            {
                if (ReadData.instance.loadedData[MapData.id][Slot_list[j].QueueId - 1] == 1)
                {
                    Slot_list[j].Paint(false);
                }
            }
            else
            {
                List<int> newFloatList = new List<int>(Slot_list.Count);
                for (int i = 0; i < Slot_list.Count; i++)
                {
                    newFloatList.Add(0); // 或者你想要的默认float值
                }
                // 将新列表添加到字典中
                ReadData.instance.loadedData.Add(MapData.id, newFloatList);
            }

           
        }
        PenController.instance. transform.gameObject.SetActive(true);
        Slot_lists = new Dictionary<int, List<Slot>>();
        Slot_lists = Partition(MapData.rows, MapData.columns, startPos);
        AdjustCamera(MapData.columns, MapData.rows);
        DetectionNotCompleted();
        StartCoroutine(MainCamera.instance.ZoomInCoroutine());
        PenController.instance.lowerPen(col, row, StartPosition[currentPiece]);
        //DisplayPieceText();

        ChangePanel.changePanel.Init_Switch_gemstone();
        PenController.instance.Set_currentTargetNumber("1");

        if (!AdManager.Instance.ShieldAddress) CheckTouch.Show();

        //ShowAllColor();
        // 打印初始统计
        //PrintNumberStats();
    }

    /// <summary>
    /// 当前块数字数量
    /// </summary>
    public Dictionary<string,List<Slot>> pieceDigitQuantity=new Dictionary<string, List<Slot>>();
    /// <summary>
    /// 当前块数字数量
    /// </summary>
    public Dictionary<string, int> DigitQuantity = new Dictionary<string, int>();

    /// <summary>
    /// 显示对应区块text
    /// </summary>
    private void DisplayPieceText()
    {
        if (Slot_lists.ContainsKey(currentPiece))
        {
            pieceDigitQuantity = new Dictionary<string, List<Slot>>();
            DigitQuantity = new Dictionary<string, int>();
            for (int i = 0; i < Slot_lists[currentPiece].Count; i++)
            {
                //Slot_lists[currentPiece][i].gameObject.SetActive(true);
                Slot_lists[currentPiece][i].OpenConsumption();
                
                if (pieceDigitQuantity.ContainsKey(Slot_lists[currentPiece][i].id))
                {
                    pieceDigitQuantity[Slot_lists[currentPiece][i].id].Add(Slot_lists[currentPiece][i]);
                    if(Slot_lists[currentPiece][i].GetisPainted())
                    {
                        DigitQuantity[Slot_lists[currentPiece][i].id]++;
                    }
                }
                else
                {
                    pieceDigitQuantity.Add(Slot_lists[currentPiece][i].id,new List<Slot>());
                    pieceDigitQuantity[Slot_lists[currentPiece][i].id].Add(Slot_lists[currentPiece][i]);
                    if (Slot_lists[currentPiece][i].GetisPainted())
                    {
                        DigitQuantity.Add(Slot_lists[currentPiece][i].id, 1);
                    }
                    else
                    {
                        DigitQuantity.Add(Slot_lists[currentPiece][i].id, 0);
                    }
                }
            }
        }
    }



    /// <summary>
    /// 检测未完成的块
    /// </summary>
    private void DetectionNotCompleted()
    {
      foreach(int key in Slot_lists.Keys)
        {
            if(!currentPieceComplete(key))
            {
                upcurrentPiece = currentPiece;
                currentPiece = key;
                DisplayBlocks(false);
                return;
            }
        }
    }



    /// <summary>
    /// 当前块是否完成 
    /// </summary>
    private bool currentPieceComplete(int id)
    {
        if (!Slot_lists.ContainsKey(currentPiece))
        {
            return false;
        }
        bool complete = true;
        for (int j = 0; j < Slot_lists[id].Count; j++)
        {
            if (Slot_lists[id][j].GetisPainted() != true)
            {
                complete = false;
            }
        }
        return complete;
    }


    /// <summary>
    /// 下一个区块
    /// </summary>
    public void NextPiece(bool and)
    {
        if( PenController.instance.isFinishTheGame)
        {
            return;
        }
        upcurrentPiece = currentPiece;
        if (and)
        {
            currentPiece++;
        }
        else
        {
            currentPiece--;
        }

        if (currentPiece > Slot_lists.Count)
        {
            currentPiece = 1;
        }
        else
        if (currentPiece < 1)
        {
            currentPiece = Slot_lists.Count;
        }
       if(Slot_lists.Count>1)
        {
            DisplayBlocks(true);
        }
    }
    /// <summary>
    /// 切换到对应区块
    /// </summary>
    private void DisplayBlocks(bool isSwitch)
    {
        if (StartPosition.ContainsKey(currentPiece))
        {
           
            if (isSwitch)
            {
                MainCamera.instance.DisplayBlocks(col, row, StartPosition[currentPiece]);
            }
            else
            {
                PenController.instance.CalculateBoundaries(row, col, StartPosition[currentPiece]);
                MainCamera.instance.AdjustCameraPosition(col, row, StartPosition[currentPiece]);
            }

        }
        DisplayPieceText();
    }






    /// <summary>
    /// 调整相机
    /// </summary>
    private void AdjustCamera(int _columns, int _rows)
    {
        if (_columns == 52 && _rows == 48)
        {
            col = 13;
            row = 16;
        }
        else
        if (_columns < 24 && _rows < 24)
        {
            col = _columns;
            row = _rows;
        }
        else
        {
            //col = 13;
            //row = 13;

            col = MapData.columns/2+2;
            row = MapData.rows/2+2;
        }

        if (StartPosition.ContainsKey(currentPiece))
        {
            MainCamera.instance.AdjustCameraPosition(col, row, StartPosition[currentPiece]);
            PenController.instance.CalculateBoundaries(row, col, StartPosition[currentPiece]);

        }
    }

    /// <summary>
    /// 分块
    /// </summary>
    /// <param name="columns"></param>
    /// <param name="rows"></param>
    /// <returns></returns>
    private Dictionary<int, List<Slot>> Partition(int rows, int columns, Vector3 pos)
    {
        // 参数验证

        Dictionary<int, List<Slot>> result = new Dictionary<int, List<Slot>>();
        StartPosition = new Dictionary<int, Vector3>();
        if (columns == 52 && rows == 48)
        {
            // 区域1: 52行 x 48列 (区块大小: 13行 x 16列)
            for (int blockRow = 0; blockRow < 4; blockRow++)       // 52/13=4 行区块
            {
                for (int blockCol = 0; blockCol < 3; blockCol++)   // 48/16=3 列区块
                {
                    List<Slot> block = new List<Slot>();
                    int startRow = blockRow * 13;
                    int startCol = blockCol * 16;

                    int currentIndex = blockRow * 3 + blockCol;
                    StartPosition.Add(currentIndex + 1, new Vector3(
                        pos.x + startRow * 1f,
                        pos.y,
                        pos.z - startCol * 1f
                    ));

                    // 遍历区块内的每个槽位
                    for (int r = 0; r < 13; r++)
                    {
                        for (int c = 0; c < 16; c++)
                        {
                            // 正确的索引计算：行索引 * 总列数 + 列索引
                            int globalRow = startRow + r;
                            int globalCol = startCol + c;
                            int index = globalRow + globalCol * 52;
                            // 添加边界检查
                            if (index >= 0 && index < Slot_list.Count)
                            {
                                block.Add(Slot_list[index]);
                            }
                        }
                    }
                    result.Add(currentIndex + 1, block);
                }
            }
        }
        else if (columns < 24 && rows < 24)
        {
            result.Add(1, Slot_list);
            StartPosition.Add(1, pos);
        }
        else
        {
            int Long= Mathf.CeilToInt(columns / 2f);
            int wide= Mathf.CeilToInt(rows / 2f);

            for (int blockRow = 0; blockRow < 2; blockRow++)
            {
                for (int blockCol = 0; blockCol < 2; blockCol++)
                {
                    List<Slot> block = new List<Slot>();
                    int startRow = blockRow * Long;
                    int startCol = blockCol * wide;

                    // 计算区块索引（行优先）
                    int blockIndex = blockRow *2 + blockCol;

                    StartPosition.Add(blockIndex + 1, new Vector3(
                       pos.x + startRow * 1f,
                       pos.y,
                       pos.z - startCol * 1f
                   ));

                    // 遍历12x12区块内的每个槽位
                    for (int r = 0; r < Long; r++)
                    {
                        for (int c = 0; c < wide; c++)
                        {
                            int globalRow = startRow + r;
                            int globalCol = startCol + c;

                            // 检查是否超出总行/列范围
                            if (globalRow >= columns || globalCol >= rows)
                                continue; // 超出范围则跳过

                            // 计算槽位索引（假设Slot_list是按行主序存储的）
                            //int index = globalRow + globalCol*rows;
                            int index = globalRow + globalCol * columns;
                            if (index >= 0 && index < Slot_list.Count)
                            {
                                block.Add(Slot_list[index]);
                            }
                        }
                    }
                    result.Add(blockIndex + 1, block);
                }
            }



        }
        return result;
    }

    /// <summary>
    /// 涂装
    /// </summary>
    public void Painting(string number)
    {
        paintedCountDict[number]++;
        current_num++;
       
        ChangePanel.changePanel.UpProgress(number);
        amount = (float)paintedCountDict[number] / numberSlotsDict[number].Count;
        if (currentPieceComplete(currentPiece))
        {
            NextPiece(true);
        }
        
       
        if (isComplete(number))///当前数字涂装完成
        {
            bool isCurrent = false;
            //if (PenController.instance.isStartTheGame)
            //{
            //    StartCoroutine(_PlayNumberOneCompleteEffect(number, numberSlotsDict));
            //}
            for (int i =0; i < MapData.mapArray_list.Count ; i++)
            {
                if (!isComplete(MapData.mapArray_list[i]))
                {
                    PenController.instance.Set_currentTargetNumber(MapData.mapArray_list[i]);
                    return;
                }
            }
        }

      


    }


    /// <summary>
    /// 测试全部颜色
    /// </summary>
    private void ShowAllColor()
    {
        for (int i = 0; i < Slot_list.Count; i++)
        {
            Slot_list[i].Paint(false);
        }
    }


    /// <summary>
    /// 打开Ui
    /// </summary>
    /// <param name="delay"></param>
    /// <returns></returns>
    IEnumerator RestoreUICoroutine(float delay = 0.5f)
    {
        ChangePanel.changePanel.GameCompleted();
        // 等待指定时间
        yield return new WaitForSeconds(delay);

        // 确保对象未被销毁
        if (this == null) yield break;

        // 调用恢复UI的方法
        ChangePanel.changePanel.RestoreUI();
    }
    /// <summary>
    /// 当前涂鸦是否完成 完成返回true
    /// </summary>
    /// <returns></returns>
    public bool isComplete(string _id)
    {
        if (!paintedCountDict.ContainsKey(_id) || !numberSlotsDict.ContainsKey(_id) || numberSlotsDict[_id].Count <= 0)
        {
            return false;
        }
        return paintedCountDict[_id] >= numberSlotsDict[_id].Count;
    }

    /// <summary>
    /// 通关
    /// </summary>
    /// <returns></returns>
    public string GetNextOne()
    {
        string str = "0";
        foreach (string key in numberSlotsDict.Keys)
        {
            if (paintedCountDict[key] < numberSlotsDict[key].Count)
            {
                return key;
            }
        }
        if (current_num >= need_num)
        {
            Debug.Log("过关");

            //OpenAll();
         
            AudioManager.Instance.Play("欢呼鼓掌");
            MainCamera.instance.zoomOut(MapData.columns, MapData.rows, StartPosition[currentPiece]);
            float tileSize = 1f;
            float mapWidth = MapData.columns * tileSize;
            float mapHeight = MapData.rows * tileSize;
            PenController.instance.FinishTheGame();

            SettlementEffect.transform.position = new Vector3(
            transform.position.x + (mapWidth / 2) - 0.5f,
            transform.position.y,
            transform.position.z - (mapHeight / 2)
             );
            //MainCamera.instance.AdjustCameraPosition(100, 100, transform.position);

            PlayerPrefs.SetInt(MapData.id.ToString(), 1);

            ChangePanel.changePanel.GameCompleted();
            ReadData.instance.ClearLoadedData(MapData.id);
            SettlementEffect.Play();
        }
        return str;
    }
    /// <summary>
    /// 打开全部
    /// </summary>
    private void OpenAll()
    {
        if(Slot_lists.Count>1)
        {
            for (int i = 0; i < Slot_list.Count; i++)
            {
                Slot_list[i].gameObject.SetActive(true);
            }
        }
    }

    /// <summary>
    /// 显示对应数字特效
    /// </summary>
    /// <param name="_id"></param>
    /// <param name="_numberSlotsDict"></param>
    /// <returns></returns>
    public IEnumerator _PlayNumberOneCompleteEffect(string _id, Dictionary<string, List<Slot>> _numberSlotsDict)
    {
        //Dictionary<string, List<Slot>> _numberSlotsDict = numberSlotsDict;
        foreach (Slot slot in _numberSlotsDict[_id])
        {
            // 检查slot是否被销毁或禁用
            if (slot == null || slot.gameObject == null || !slot.gameObject.activeInHierarchy)
            {
                continue;
            }
          
            slot.PlayParticleEffect();
                yield return new WaitForSeconds(0.1f);
            
        }
    }

    
    // 打印数字统计信息
    void PrintNumberStats()
    {
        foreach (var pair in numberSlotsDict)
        {
            string number = pair.Key;
            int total = pair.Value.Count;
            int painted = paintedCountDict[number];
        }
    }

   
    /// <summary>
    /// 创建对象池
    /// </summary>
    /// <returns></returns>
    private Slot CreateNewObject()
    {
        Slot newObj = Instantiate(slotPrefab);
        newObj.gameObject.SetActive(false);
        newObj.transform.SetParent(transform); // 设为池的子对象方便管理
        objectPool.Enqueue(newObj);
        return newObj;
    }

    // 从池中获取对象
    public Slot GetObject()
    {
        if (objectPool.Count == 0)
        {
            // 池为空时创建新对象
            CreateNewObject();
        }

        Slot obj = objectPool.Dequeue();
        obj.gameObject.SetActive(true);
        activeSlots.Add(obj);
        return obj;
    }

    // 将对象返回池中
    public void ReturnObject(Slot obj)
    {
        obj.Init();
        obj.gameObject.SetActive(false);
        obj.transform.SetParent(transform); // 重置父对象
        objectPool.Enqueue(obj);
        activeSlots.Remove(obj); // 从激活列表移除
    }
    /// <summary>
    /// 全部返回
    /// </summary>
    public void ReturnAllSlots()
    {
        // 创建临时列表避免修改正在迭代的集合
        List<Slot> slotsToReturn = new List<Slot>(activeSlots);

        foreach (Slot slot in slotsToReturn)
        {
            ReturnObject(slot);
        }
    }



}
